<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="参数名称" prop="configNameLike">
        <el-input
          v-model="queryParams.configNameLike"
          placeholder="请输入参数名称"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参数键名" prop="configKeyLike">
        <el-input
          v-model="queryParams.configKeyLike"
          placeholder="请输入参数键名"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统内置" prop="configType">
        <el-select v-model="queryParams.configType" placeholder="系统内置" clearable size="default" style="width: 240px">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="default"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['system:config:search']" />
        <reset-button @click="resetQuery" :perm="['system:config:search']" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['system:config:insert']" :roleType="['conf']" />
      <delete-button
        @click="handleDelete"
        :disabled="multiple"
        :perm="['system:config:delete']"
        :roleType="['conf']"
      />
      <export-button @click="handleExport" :perm="['system:config:export']" />
      <clear-button
        @click="handleClearCache"
        :perm="['monitor:config:cache']"
        :roleType="['conf']"
        text="清理缓存"
      />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['system:config:search']"
      />
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="参数主键" align="center" prop="configId" />
      <el-table-column
        label="参数名称"
        align="center"
        prop="configName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="参数键名"
        align="center"
        prop="configKey"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="参数键值" align="center" prop="configValue" />
      <el-table-column label="系统内置" align="center" prop="configType">
        <template #default="scope">
          <span :class="scope.row.configType === 'Y' ? 'text-danger' : ''">{{
            selectDictLabel(typeOptions, scope.row.configType)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="hasRoleType(['conf'])"
      >
        <template #default="scope">
          <text-edit-button
            @click="handleUpdate(scope.row)"
            :perm="['system:config:update']"
            :roleType="['conf']"
          />
          <text-delete-button
            @click="handleDelete(scope.row)"
            :perm="['system:config:delete']"
            :subject="scope.row.configName"
            :roleType="['conf']"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="form.configType">
            <el-radio v-for="dict in typeOptions" :key="dict.dictValue" :value="dict.dictValue">{{
              dict.dictLabel
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import {
  listConfig,
  getConfig,
  delConfig,
  addConfig,
  updateConfig,
  exportConfig,
  clearCache,
  checkConfigKeyIfUnique
} from '@base/api/base/config'
import { debounceWrapper } from '@/utils/zmids'

export default {
  name: 'BaseConfig',
  data() {
    const checkConfigKeyUniqueRule = (rule, value, callback) => {
      checkConfigKeyIfUnique(value, this.form.configId).then((response) => {
        if (response.data === true) {
          callback('系统参数已存在')
        } else {
          callback()
        }
      })
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderBy: 'UPDATE_TIME',
        sortDirect: 'DESC',
        configNameLike: undefined,
        configKeyLike: undefined,
        configType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        configName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
        configKey: [
          { required: true, message: '参数键名不能为空', trigger: 'blur' },
          { required: true, validator: checkConfigKeyUniqueRule, trigger: 'blur' }
        ],
        configValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_yes_no').then((response) => {
      this.typeOptions = response.data
    })
  },
  methods: {
    /** 查询参数列表 */
    getList: debounceWrapper(function () {
      this.loading = true
      listConfig(
        this.addDateRange(this.queryParams, ['createTimeStart', 'createTimeEnd'], this.dateRange)
      ).then((response) => {
        this.configList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    }),
    // 参数系统内置字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.configType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        configId: undefined,
        configName: undefined,
        configKey: undefined,
        configValue: undefined,
        configType: 'N',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加参数'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.configId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate: debounceWrapper(function (row) {
      this.reset()
      const configId = row.configId || this.ids[0]
      getConfig(configId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改参数'
      })
    }),
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.configId != undefined) {
            updateConfig(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addConfig(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const configIds = row ? row.configId : this.ids.join(',')
      delConfig(configIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.downloadUrl(
        '/system/config/export',
        this.addDateRange(this.queryParams, ['createTimeStart', 'createTimeEnd'], this.dateRange)
      )
    },
    /** 清理缓存按钮操作 */
    handleClearCache() {
      clearCache().then((res) => {
        if (res.code === '200') {
          this.msgSuccess('清理成功')
        } else {
          this.msgError(res.msg)
        }
      })
    }
  }
}
</script>
